package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import persistence.Axdbv4HibernateManager;

public class StatisticsServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		System.out.println("Avviata StatisticsServlet");
		sendBackStatisticsXML(resp);
		
	}
	
	
	private void sendBackStatisticsXML(HttpServletResponse resp){
		
		resp.setContentType("text/html; charset=UTF-8");
		Axdbv4HibernateManager dbManager=Axdbv4HibernateManager.getIstance();
		HashMap<String, Integer> statistics=(HashMap<String, Integer>) dbManager.getStatistics();
		try {
			PrintWriter out = resp.getWriter();
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder;
			docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			// root elements
			Element rootElement = doc.createElement("Stats");
			doc.appendChild(rootElement);
			
			for (String key : statistics.keySet()) {
				Element stat = doc.createElement("stat");
				rootElement.appendChild(stat);
				//TODO non si usa quindi l'ho completata
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
	}

}
